import React, { useState } from 'react';
import { Form, Input, Button, Select, Table, Row, Col } from 'antd';
const { Option } = Select;

const layout = {
  labelCol: {
    span: 8,
  },
  wrapperCol: {
    span: 16,
  },
};

const SForm = ({ add }) => {
  const [form] = Form.useForm();

  /** 添加 */
  const btnQuery = async() => {
    const values = await form.validateFields(); // 触发表单验证
    add(values);
  };

  /** 重置 */
  const onReset = () => {
    form.resetFields();
  };

  return (
    <Form {...layout} form={form} name="control-hooks">
      <Row>
        <Col span={8}>
          <Form.Item name="userName" label="用户名称">
            <Input placeholder='请输入用户名称' />
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item name="userStatus" label="用户状态">
            <Select>
              <Option value='up'>上线</Option>
              <Option value='done'>下线</Option>
            </Select>
          </Form.Item>
        </Col>
        <Col span={8}>
          <Form.Item>
            <Button onClick={btnQuery} type="primary" htmlType="submit">
              添加
            </Button>
            <Button htmlType="button" onClick={onReset}>
              重置
            </Button>
          </Form.Item>
        </Col>
      </Row>
    </Form>
)}

/**
 * 子组件-表格
 * @param dataList 表格数据
 * @returns 
 */
const STable = ({dataList}) => {
  const columns = [
    {
      title: '用户姓名',
      dataIndex: 'userName',
      key: 'userName'
    },
    {
      title: '用户状态',
      dataIndex: 'userStatus',
      key: 'userStatus',
      render: (record) => record === 'up' ? '上线' : '下线'
    }
  ];
  return <Table dataSource={dataList} columns={columns} rowKey={(record) => record?.lendth + 1} />
}

/** 父组件 使用了hooks方法实现 */
const TableForm = () => {
  const [tableData, setTableData] = useState([]);

  /**
   * 添加方法
   * @param {*} formValue 表单参数
   */
  const add = (formValue) => {
    let a = tableData.concat([formValue]);
    setTableData(a);
  }

  return (
    <>
      <div style={{ marginTop: 40 }}>
        <SForm add={add} />
      </div>
      <div style={{ padding: 20 }}>
        <STable dataList={tableData} />
      </div>
    </>
  )
}
export default TableForm;